import re

from django import http
from django.contrib.auth.backends import ModelBackend

from .models import User

''' 判断是否为手机用户，如果是则返回手机号为登录用户'''
def get_user_by_account(account):

    try:

        if re.match('^1[3-9]\d{9}$',account):

            user = User.objects.get(mobile=account)

        else:

            user = User.objects.get(username=account)

    except  Exception as e:

        return http.JsonResponse({'code':400,
                                  'errmsg':'用户不存在'})
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        user = get_user_by_account(username)

        if user and user.check_password(password):

            return user













